package util;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.opensaml.DefaultBootstrap;
import org.opensaml.saml2.core.ArtifactResolve;
import org.opensaml.xml.Configuration;
import org.opensaml.xml.io.Unmarshaller;
import org.opensaml.xml.io.UnmarshallerFactory;
import org.opensaml.xml.util.XMLHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class SamlResponse {

	private String issuer = null;
	private String artifact = null;

	public void decode(String token) throws Exception {

		DefaultBootstrap.bootstrap();

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(new ByteArrayInputStream(token
				.getBytes()));
		Element element = document.getDocumentElement();

		//System.out.println("element " + element);
		//System.out.println("local name " + element.getLocalName());
		// System.out.println("local name "+element.getElementsByTagName("ArtifactResolve").item(0).getLocalName());
		//System.out.println("Unmarshalling SAML document root element{}" + XMLHelper.getNodeQName(element));

		// ArtifactResolveUnmarshaller unmarshaller = new
		// ArtifactResolveUnmarshaller();
		UnmarshallerFactory unmarshallerFactory = Configuration
				.getUnmarshallerFactory();
		//System.out.println("unmarshallerFactory " + unmarshallerFactory);
		Unmarshaller unmarshaller = unmarshallerFactory
				.getUnmarshaller(element);
		Logger.Log("unmarshaller " + unmarshaller);
		//System.out.println("node name " + element.getNodeName());
		if (unmarshaller != null) {
			ArtifactResolve artifactResolve = (ArtifactResolve) unmarshaller
					.unmarshall(element);
			this.issuer = artifactResolve.getIssuer().getValue();
			Logger.Log("Issuer " + this.issuer);
			this.artifact = artifactResolve.getArtifact().getArtifact();
			Logger.Log("Artifact " + this.artifact);
		}
	}

	public String getIssuer() {
		return issuer;
	}

	public void setIssuer(String issuer) {
		this.issuer = issuer;
	}

	public String getArtifact() {
		return artifact;
	}

	public void setArtifact(String artifact) {
		this.artifact = artifact;
	}

	public static void main(String[] args) {
		try {
			String token = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><saml2p:ArtifactResolve IssueInstant=\"2012-05-04T02:00:18.145Z\" Version=\"2.0\" xmlns:saml2p=\"urn:oasis:names:tc:SAML:2.0:protocol\"><saml2:Issuer xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">HP.com</saml2:Issuer><saml2p:Artifact>5bb144ef5ca52791c9bcfe76c3826</saml2p:Artifact></saml2p:ArtifactResolve>";

			SamlResponse saml = new SamlResponse();
			saml.decode(token);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
